package com.zbkj.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zbkj.common.dto.TuHuLocationDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: bigcoolfork
 * Date: 2021/11/12
 * Time: 10:35
 * Description: 测试DEMO
 */
@Slf4j
public class TuHuUtil {

    //获取AccessToken
    public static final String getAccessTokenUrl = "http://open.tuhugc.com/v1/token/get";
    //根据IMEI获取最新定位数据
    public static final String getLocationUrl = "http://open.tuhugc.com/v1/device/location/get";

//    private static final String openapi_url = "openAPI地址";

    // 申请来的appKey和appSecret
    public static final String app_key = "6869596f12a696f9cd4373d29540d243";
    public static final String app_secret = "697bf84c33fb35010acb369208b59af0";
    //主账号
    public static final String userId = "18353360235";
    //AccessToken过期时间，单位秒
    public static final Long expireTime = 7200l;

    /**
     * 请求途狐api
     *
     * @param headerMap
     * @param paramMap
     * @param url
     * @return
     */
    public static String sendPost(Map<String, String> headerMap, Map<String, String> paramMap, String url) {
        try {
            HttpPost post = new HttpPost(url);
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : paramMap.keySet()) {
                list.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
            post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            if (null != headerMap) {
                post.setHeaders(assemblyHeader(headerMap));
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(post);
            org.apache.http.HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity, "utf-8");
            return s;
//            JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
//            Boolean b = (Boolean) jsonObject.get("success");
//            if (b) {
//                JSONObject j = (JSONObject) jsonObject.get("result");
//                String accessToken = (String) j.get("accessToken");
//                return accessToken;
//            }
        } catch (IOException e) {
            System.err.println(e);
        }
        return "";
    }


    /**
     * 组装头部信息
     *
     * @param headers
     * @return
     */
    private static Header[] assemblyHeader(Map<String, String> headers) {
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }


    public static List<TuHuLocationDto> getLocationByImei(String imei, String accessToken) {
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("X-Access-Token", accessToken);
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("imeis", imei);
        paramMap.put("mapType", "GOOGLE");
        makeParam(headerMap, paramMap);

        String s = TuHuUtil.sendPost(headerMap, paramMap, TuHuUtil.getLocationUrl);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
        Integer code = (Integer) jsonObject.get("code");
        if (0 == code) {
            JSONArray jsonArray = (JSONArray) jsonObject.get("result");
            List<TuHuLocationDto> list = jsonArray.toJavaList(TuHuLocationDto.class);
            return list;
        } else {
            log.info("获取accessToken失败...错误码是{}", code);
        }
        return new ArrayList<>();
    }

    /**
     * 获取AccessToken
     *
     * @return
     */
    public static String getAccessToken() {
        Map<String, String> headerMap = new HashMap<String, String>();
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("userId", userId);
        makeParam(headerMap, paramMap);

        //获取accessToken
        String accessToken = "";
        String s = TuHuUtil.sendPost(headerMap, paramMap, TuHuUtil.getAccessTokenUrl);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
        Integer code = (Integer) jsonObject.get("code");
        if (0 == code) {
            JSONObject j = (JSONObject) jsonObject.get("result");
            accessToken = (String) j.get("accessToken");
            return accessToken;
        } else {
            log.info("获取accessToken失败...错误码是{}", code);
        }
        return "";
    }


    public static void makeParam(Map<String, String> headerMap, Map<String, String> paramMap) {
        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
        // 先调用获取token接口获取token，获取到的token配置在请求头中，再去请求其它接口
        // headerMap.put("X-Access-Token", "xxxxxxxxxxxxxx");
        // 公共参数
        paramMap.put("appKey", TuHuUtil.app_key);
        paramMap.put("v", "1.0");
        paramMap.put("timestamp", DateUtil.timeOfLongToStr(System.currentTimeMillis()));
        paramMap.put("signMethod", "md5");
        paramMap.put("format", "json");

        //私有参数_获取token
        //userId为分配密钥对应的账户的手机号码

        paramMap.put("expiresIn", "7200");

        //私有参数_根据账户，获取该账户下的所有IMEI信息
        //paramMap.put("userId", "您的用户名");

        // 计算签名
        String sign = "";
        try {
            sign = SignUtils.signTopRequest(paramMap, TuHuUtil.app_secret, "md5");
            paramMap.put("sign", sign);
            System.out.println(sign);
        } catch (IOException e) {
            System.err.println(e);
        }

    }


}